package my.study.com.mysql.jdbc.examples.example1;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class Ex1 {

	/**
	 * Retrieving AUTO_INCREMENT column values using
	 * Statement.getGeneratedKeys()
	 * 
	 * @param args
	 * @throws ClassNotFoundException
	 * @throws IllegalAccessException
	 * @throws InstantiationException
	 * @throws SQLException
	 */
	public static void main(String[] args) throws InstantiationException,
			IllegalAccessException, ClassNotFoundException, SQLException {
		String url = "jdbc:mysql://tc-dba-crm-test00.tc.baidu.com:8806/crm_db";
		String user = "crm";
		String password = "123456";

		//Class.forName("com.mysql.jdbc.Driver");
		// Class.forName("com.mysql.jdbc.Driver").newInstance();
		Connection conn = DriverManager.getConnection(url, user, password);
		Statement stmt = null;
		ResultSet rs = null;
		try {
			stmt = conn.createStatement();
			stmt.executeUpdate("DROP TABLE IF EXISTS autoIncTutorial");
			stmt.executeUpdate("CREATE TABLE autoIncTutorial (priKey INT NOT NULL AUTO_INCREMENT, dataField VARCHAR(64), PRIMARY KEY (priKey))");
			stmt.executeUpdate("INSERT INTO autoIncTutorial (dataField) values ('Can I Get the Auto Increment Field?')",
					Statement.RETURN_GENERATED_KEYS);
			//
			// Example of using Statement.getGeneratedKeys()
			// to retrieve the value of an auto-increment
			// value
			//
			int autoIncKeyFromApi = -1;
			rs = stmt.getGeneratedKeys();
			if (rs.next()) {
				autoIncKeyFromApi = rs.getInt(1);
			} else {
				// throw an exception from here
			}
			stmt.executeUpdate("DROP TABLE IF EXISTS autoIncTutorial");
			rs.close();
			rs = null;
			System.out.println("Key returned from getGeneratedKeys():"
					+ autoIncKeyFromApi);
		} finally {
			if (rs != null) {
				try {
					rs.close();
				} catch (SQLException ex) {
					// ignore
				}
			}
			if (stmt != null) {
				try {
					stmt.close();
				} catch (SQLException ex) {
					// ignore
				}
			}
			if (conn != null) {
				conn.close();
			}
		}

	}

}
